﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class BhvLineLayout : MonoBehaviour
{


    [SerializeField] private int _count = 0;
    public int count
    {
        get => _count;
        set
        {
            _count = Mathf.Clamp(value, 0, this.transform.childCount);
            UpdateLayout();
        }
    }

    public float gridSize = 1;

    public Vector3 direction = Vector3.right;
    public float pivot = 0.5f;



#if UNITY_EDITOR
    private bool _dirty = false;
    private int _ChildCount = 0;
    private void OnValidate()
    {
        _count = Mathf.Clamp(_count, 0, this.transform.childCount);
        _dirty = true;
    }

    private void Update()
    {
        if (this.transform.childCount != _ChildCount)
        {
            _ChildCount = this.transform.childCount;
            _dirty = true;
        }

        if (_dirty)
        {
            _dirty = false;
            this.UpdateLayout();
        }
    }
#endif


    private void UpdateLayout()
    {
        int index = 0;

        foreach (Transform child in this.transform)
        {
            if (child.GetSiblingIndex() >= this.count)
            {
                child.gameObject.SetActive(false);
            }
            else
            {
                child.gameObject.SetActive(true);
            }
        }

        float offsetCount = Mathf.FloorToInt(pivot * this.count);
        if (this.count % 2 == 0) offsetCount -= 0.5f;

        foreach (Transform child in this.transform)
        {
            if ((child.gameObject.activeSelf))
            {
                child.position = this.transform.position + direction.normalized * gridSize * (index - offsetCount);
                index++;
            }


        }

    }


}
